from Definition import Definition
import handler.Console
import handler.Pyhs


class OutputDefinition(Definition):
	def __init__(self, file):
		super().__init__(file)
		self.current_state = None
		self.handler = None

		handler_name = self.content.get('handler')
		if handler_name is not None:
			self._set_handler(handler_name)

	def initialize(self, all_definitions):
		outputs = self.content.get('outputs')
		self.children = []
		if outputs is not None:
			self.children = [definition for definition in all_definitions if (
				definition != self and
				definition.content['name'] in outputs
			)]

	def _set_handler(self, handler_name):
		if handler_name == 'console':
			self.handler = handler.Console.Console(self.content)
		elif handler_name == 'pyhs':
			self.handler = handler.Pyhs.Pyhs(self.content)

	def _change_state(self, next_state):
		status = ' ' + self.content['name'] + ': ' + str(self.current_state) + ' -> ' + str(next_state)
		if self.handler is not None:
			self.handler.change_state(self.current_state, next_state)
		self.current_state = next_state
		return status

	def execute(self, values):
		next_state = values.get(self.content['name'])
		status = ''
		if self.current_state != next_state:
			status = self._change_state(next_state)

		for child in self.children:
			status += child.execute(values)

		return status

	@classmethod
	def read(cls):
		return cls.read_folder('output')
